package controller

import (
	"awesomeProject/lib"
	"github.com/gin-gonic/gin"
	"log"
)

func GetHistory(c *gin.Context) {
	var req lib.GetHistoryReq
	if err := c.ShouldBindJSON(&req); err != nil {
		log.Println("read json fail in get history")
		return
	}
	// 用户鉴权
	ok, err := AuthId(req.Id, req.Token)
	if !ok || err != nil {
		log.Println("auth fail in get history, id or password invalid")
		c.JSON(400, lib.GetHistoryResp{
			StatusCode: 1,
			StatusMsg:  "auth fail, maybe your Id or password is wrong",
		})
		return
	}
	// 搜索所有相关消息
	start := req.Start
	if start == 0 {
		start = 20000
	}
	rows, err := pool.Query("SELECT sender_id, receiver_id, sender_username, receiver_username, content, time FROM public.message"+
		" WHERE (sender_id=$1 AND receiver_id=$2 AND msg_id<$3) OR (sender_id=$4 AND receiver_id=$5 AND msg_id<$6) ORDER BY time DESC LIMIT 30;", req.Id, req.TheOtherId, start, req.TheOtherId, req.Id, start)
	if err != nil {
		log.Println("query fail in get history")
		return
	}
	var resp lib.GetHistoryResp
	cnt := 0
	for rows.Next() {
		var message lib.Message
		err := rows.Scan(
			&message.Sender.Id,
			&message.Receiver.Id,
			&message.Sender.Username,
			&message.Receiver.Username,
			&message.Content,
			&message.Time,
		)
		if err != nil {
			log.Println("scan rows fail in get history")
			return
		}
		cnt++
		message.Type = "history"
		message.IsPhoto = 0
		resp.History = append(resp.History, message)
	}
	resp.SumNum = cnt
	resp.StatusCode = 2
	resp.StatusMsg = "get history successfully"
	c.JSON(200, resp)
	return
}
